<template>
  <div class='q-pa-md bg-white'>
    <div class='row'>
      <div class='col-4' style='min-width: 250px; max-width: 300px' @mouseover='mouseover'>
        <q-select
          v-model='mulSelect.arr'
          filled
          label='选择项'
          multiple
          name='search'
          stack-label
          use-chips
        />
      </div>
      <div class='col-2'>
        <q-btn color='white' icon='search' text-color='black' @click='fetchFromServer' />
      </div>
    </div>

    <div class='q-pt-md row justify-start items-center'>
      <div v-for='(item,index) in searchFrame' :key='index' class='q-px-md'>
        <q-btn-dropdown :label='item.property_name' class='col-4' color='primary'
                        @click='onQueryBar(index+1)'>
          <q-list v-for='item in searchFrameArr' :key='item.markNo'>
            <q-item v-close-popup clickable @click='searchClick(item,index)'>
              <q-item-section>
                <q-item-label>
                  {{ item.value }}
                </q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>
      </div>
    </div>
  </div>
</template>

<script lang='ts'>
import { defineComponent, onMounted, reactive, ref } from 'vue';
import { useStore } from 'src/store';
import { postRequest } from '../components/functions';
import { OriginalRows, Pagination, Props, TableColumn } from 'components/models';

export default defineComponent({
    name: 'searchComponent.vue',
    setup() {
      const store = useStore();
      const queryMenu = 'channel/channel/queryMenu';
      const getInterface = '/channel/channel/getInterface';
      const pagination = ref<Pagination>({
        sortBy: 'desc',
        descending: false,
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10
      });
      let columns = ref<TableColumn[]>();
      const userData = store.state.sphinx.userData;
      let fromdataUrl = ref<string>('');
      let QueryBarCode = reactive({ arr: [] });
      let mulSelect = reactive({ arr: [] });
      let searchFrame = ref([]);
      const loading = ref<boolean>(false);
      let carDetailData = store.state.sphinx.CarMessage;
      let cartypeRelation = store.state.sphinx.cartypeRelation;
      let searchFrameArr = ref([]);
      const rows = ref([]);
      const originalRows = ref<OriginalRows[]>();

      // 鼠标放在搜索框上出搜索选项
      function mouseover() {
        let resData = {
          entityCode: cartypeRelation.otherEntityCode,
          entityType: cartypeRelation.otherEntityType,
          sceneCodeType: '101102' + userData.roleType + '103',
          objectCodeType: '107'//代表搜索的代码
        };
        if (searchFrame.value.length == 0) {
          postRequest(queryMenu, resData, (res: []) => {
            searchFrame.value = res;
          });
        }
      }

      //点击下拉的数据展示在搜索框里
      function searchClick(item: any, index: number) {
        let itemElement = searchFrame.value[index].property_code;
        mulSelect.arr.push(item.value);
        let obj = {};
        obj[itemElement] = item.value;
        QueryBarCode.arr.push(obj);
        mulSelect.arr = Array.from(new Set(mulSelect.arr));
      }

      // 点击搜索框获取数据
      function onQueryBar(i) {
        //获取搜索数据的接口
        let resData = {
          entityCode: cartypeRelation.otherEntityCode,
          entityType: cartypeRelation.otherEntityType + '1070' + i,
          theirEventCode: '001'
        };
        let QueryBarUrl = ref<string>('');
        postRequest(getInterface, resData, res => {
          QueryBarUrl.value = res.data.interfaceEnglish;
        });

        //获取搜索条件
        let resData1 = {
          entityCode: cartypeRelation.otherEntityCode,
          entityType: cartypeRelation.otherEntityType,
          sceneCodeType: '101102' + userData.roleType + '103',
          objectCodeType: '1070' + i
        };
        let QueryBarData = ref({});
        postRequest(queryMenu, resData1, res => {
          res.forEach(i => {
            let obj = {};
            obj[i.property_code] = '';
            QueryBarData.value = obj;
          });
        });

        //获取搜索数据
        searchFrameArr.value = [];
        setTimeout(() => {
          postRequest(QueryBarUrl.value, QueryBarData.value, res => {
            searchFrameArr.value = res;
          });
        }, 1000);
      }

      /**
       * 请求关系首页表头
       */
      function requestColumns() {
        let reqData = reactive({});
        reqData = {
          entityCode: cartypeRelation.otherEntityCode,
          entityType: cartypeRelation.otherEntityType,
          sceneCodeType: '101102' + userData.roleType + '103',//渠道101+当事人102+用户角色userData.roleType（例：01为管理员）+场景主体
          objectCodeType: '102'//关系首页表头
        };
        postRequest(queryMenu, reqData, getColums);
      }

      /**
       * 设置列名
       * @param resultData
       */
      function getColums(resultData: TableColumn[] | any) {
        let newArr = [];
        if (resultData !== undefined && resultData !== null && resultData.length > 0) {
          resultData.forEach(item => {
            newArr.push({ name: item.property_code, label: item.property_name, field: item.property_code });
          });
        }
        columns.value = newArr;
      }

      // 获取请求表内数据的接口
      function getFromdataUrl() {
        let data = {
          entityCode: cartypeRelation.otherEntityCode,
          entityType: cartypeRelation.relationCode,
          theirEventCode: '001' //查询
        };
        postRequest(getInterface, data, res => {
          fromdataUrl.value = res.data.interfaceEnglish;
        });
      }

      /**
       * 请求表内数据
       * @param startRow
       * @param count
       * @param filter
       * @param sortBy
       * @param descending
       */
      function fetchFromServer(startRow: number, count: number, filter: string, sortBy: string, descending: boolean) {
        //处理搜索内容的数据
        let newArr = ref([]);
        QueryBarCode.arr.forEach(x => {
          mulSelect.arr.forEach(y => {
            if (y == Object.values(x)[0]) {
              newArr.value.push(x);
            }
          });
        });
        let target = reactive({
          companyId: cartypeRelation.companyId,
          theirEntityCode: cartypeRelation.otherEntityCode,
          theirEntityCodeName: cartypeRelation.otherEntityCodeName,
          theirEntityType: cartypeRelation.otherEntityType,
          theirEntityTypeName: cartypeRelation.otherEntityTypeName,

          otherEntityCode: cartypeRelation.entityCode,
          otherEntityCodeName: cartypeRelation.otherEntityCodeName,
          otherEntityNo: carDetailData.storeNo,
          otherEntityType: cartypeRelation.entityType,
          otherEntityTypeName: cartypeRelation.typeName,
          otherEntityNoName: carDetailData.storeName,

          relationCode: cartypeRelation.relationCode,
          relationName: cartypeRelation.relationName,
          eventCode: '001'
        });

        // 批量增加
        // let data = {
        //   theirEntityCode: cartypeRelation.otherEntityCode,
        //   relationCode: cartypeRelation.relationCode,
        //   eventCode: '302'
        // };

        if (newArr.value.length != 0) {
          newArr.value.forEach(item => {
            Object.assign(target, item);
          });
        }
        postRequest(fromdataUrl.value, target, (data) => {
          searchFrame.value.length = 0;
          // mulSelect.arr.length = 0;
          rows.value = data;
        });
      }



      /**
       * 计算分页
       * @param filter
       */
      function getRowsNumberCount(filter: string): number {
        let count = 0;
        if (originalRows.value !== undefined) {
          if (!filter) {
            return originalRows.value.length;
          }
          originalRows.value.forEach((treat: OriginalRows) => {
            if (treat.name.includes(filter)) {
              ++count;
            }
          });
        }
        return count;
      }

      /**
       * 数据请求
       * @param props
       */
      function onRequest(props: Props) {
        const { page, rowsPerPage, sortBy, descending } = props.pagination;
        const filter = props.filter;
        loading.value = true;
        // emulate server
        setTimeout(() => {
          // update rowsCount with appropriate value
          pagination.value.rowsNumber = getRowsNumberCount(filter);
          // get all rows if "All" (0) is selected
          const fetchCount = rowsPerPage === 0 ? pagination.value.rowsNumber : rowsPerPage;
          // calculate starting row of data
          const startRow = (page - 1) * rowsPerPage;
          // fetch data from "server"
          fetchFromServer(startRow, fetchCount, filter, sortBy, descending);
          // clear out existing data and add new
          // don't forget to update local pagination object
          pagination.value.page = page;
          pagination.value.rowsPerPage = rowsPerPage;
          pagination.value.sortBy = sortBy;
          pagination.value.descending = descending;
          // ...and turn of loading indicator
          loading.value = false;
        }, 1500);
      }

      /**
       * 组合请求
       */
      function requestTableData() {
        requestColumns();
        getFromdataUrl();
        // get initial data from server (1st page)
        onRequest({
          pagination: pagination.value,
          filter: ''
        });
      }

      onMounted(() => {
        requestTableData();
      });

      return {
        requestColumns,
        onRequest,
        loading,
        pagination,
        columns,
        rows,
        getFromdataUrl,
        fromdataUrl,
        searchFrame,
        mulSelect,
        fetchFromServer,
        userData,
        carDetailData,
        mouseover,
        cartypeRelation,
        searchFrameArr,
        onQueryBar,
        searchClick
      };
    }
  }
);

</script>

<style scoped>

</style>
